package com.gnerv.cms.service.impl;

import com.gnerv.cms.common.CommonString;
import com.gnerv.cms.entity.Task;
import com.gnerv.cms.service.ITriggerService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.TimeZone;

@Slf4j
@Service
public class TriggerServiceImpl implements ITriggerService {

    @Resource
    Scheduler scheduler;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Trigger createTrigger(Task task) {
        String cronExpression = String.format(task.getCron());
        CronScheduleBuilder cronScheduleBuilder;
        try {
            cronScheduleBuilder = CronScheduleBuilder
                    .cronSchedule(cronExpression)
                    // 不对MisFire的任务做任何处理，错过了就是错过了
                    .withMisfireHandlingInstructionDoNothing()
                    .inTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        } catch (Exception e) {
            log.info("cron表达式错误");
            throw new RuntimeException("cron表达式错误");
        }
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(task.getUkId(), CommonString.TASK_GROUP_NAME)
                .withSchedule(cronScheduleBuilder)
                .build();
        return trigger;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean deleteTrigger(String taskId) {
        boolean b = checkTrigger(taskId);
        if (b) {
            try {
                scheduler.unscheduleJob(TriggerKey.triggerKey(taskId, CommonString.TASK_GROUP_NAME));
            } catch (SchedulerException e) {
                log.info("触发器移除失败");
            }
        }
        return true;
    }

    @Override
    public boolean checkTrigger(String taskId) {
        boolean exists = true;
        try {
            exists = scheduler.checkExists(TriggerKey.triggerKey(taskId, CommonString.TASK_GROUP_NAME));
        } catch (SchedulerException e) {
            log.info("触发器不存在");
        }
        return exists;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean stopTrigger(String taskId) {
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(taskId, CommonString.TASK_GROUP_NAME));
        } catch (SchedulerException e) {
            log.info("触发器停止失败");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean startTrigger(String taskId) {
        try {
            scheduler.resumeTrigger(TriggerKey.triggerKey(taskId, CommonString.TASK_GROUP_NAME));
            // 暂停任务后 恢复任务时立即执行一次任务
            scheduler.triggerJob(JobKey.jobKey(taskId, CommonString.TASK_GROUP_NAME));
        } catch (SchedulerException e) {
            log.info("触发器启动失败");
        }
        return true;
    }


}
